<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @author Administrator
 *        
 */
class Regions extends CI_Controller{
	
	protected $class_name;
	protected $dwt_list;
	protected $dwt_info;
	protected $myModel;
	protected $datas;
	protected $fork = ''; //所属子目录
	
	function __construct() {
		parent::__construct ();
		$this->class_name = strtolower ( __CLASS__ );
			
		$my_model = $this->class_name . '_model';
		if(!empty($this->fork)){
			$this->datas ['my_position'] = $this->fork . '_' . $this->class_name;
			$this->datas ['my_router'] = $this->fork . '/' . $this->class_name;
			$this->load->model ( $this->fork . '/' . $my_model );
	
			$this->dwt_list = $this->fork . '/' . $this->class_name . '_list';
			$this->dwt_info = $this->fork . '/' . $this->class_name . '_info';
		}else{
			$this->datas ['my_position'] = $this->class_name;
			$this->datas ['my_router'] = $this->class_name;
			$this->load->model ( $my_model );
	
			$this->dwt_list = $this->class_name . '_list';
			$this->dwt_info = $this->class_name . '_info';
		}
		$this->dwt_info_modal = 'pages/' . $this->dwt_info . '_modal.php';
		$this->myModel = $this->$my_model;
	
		$this->datas ['full_page'] = true;
		$this->datas ['page_title'] = "城市地区列表";

	}
	/**
	 * 仅作为ZS链接模型用
	 */
	protected function link_model() {
		exit ();
		$this->load->model ( 'regions_model' );
	}
	
	public function index() 
	{
		$get = $this->input->get ();
		$parent_id = isset($get['parent_id']) ? intval($get['parent_id']) : 0;
		
		$parent_info = array('region_id' => $parent_id, 'parent_id' => 0);
		$back_url = 'regions';
		if($parent_id > 0){
			$parent_info = $this->myModel->get_info($parent_id);
			if($parent_info['parent_id'] > 1){
				$back_url = 'regions?parent_id='.$parent_info['parent_id'];
			}
			$this->datas ['page_title'] .= "【".$parent_info['region_name']."】";
		}
		$parent_info['back_url'] = site_url($back_url);
		$this->datas ['parent_info'] = $parent_info;
		$this->query_list ();
	}

	/**
	 * 分页数据
	 *
	 * @param number $page        	
	 */
	private function query_list($page = 1, $filter = array(), $load_page = TRUE) {
		$get = $this->input->get ();
		if (! empty ( $get )) {
			$filter = array_merge ( $filter, $get );
		}
		if (isset ( $filter ['page'] ) && $filter ['page'] > 0) {
			$page = $filter ['page'];
		}
		
		$item_list = $this->myModel->get_list ( $filter, $page );
		$this->datas ['lists'] = $item_list ['list'];
		$this->datas ['pager'] = $item_list ['pager'];
		
		if ($this->datas ['full_page']) {
			$this->load->view ( $this->dwt_list, $this->datas );
		} else {
			return $this->load->view ( $this->dwt_list, $this->datas, TRUE );
		}
	}
	
	public function get($region_type, $parent_id)
	{
		$parent_info = $this->myModel->get_region_info($parent_id);
		$region_list = $this->myModel->get_regions($region_type, $parent_id);
		if(!empty($region_list)){
			$restr = '';
			foreach ($region_list as $row){
				$format = '<option value="%d" data-municipality="%d" data-aboard="%d" data-start="%d">%s %s</option>';
				$restr .= sprintf($format, $row['region_id'], $row['municipality'], $row['is_aboard'], $row['is_start'], strtoupper($row['initial']), $row['region_name']);
			}
			make_json_result($restr, 'ok', $parent_info);
		}else{
			make_json_error("请求失败！[Err:601]");
		}
	}
	/**
	 * 接收ajax请求
	 * @param unknown $action
	 * @param number $item_id
	 */
	public function ajax($action, $item_id = 0)
	{
		$datas = $this->input->get();
		$datas['item_id'] = $item_id;
		$this->process_ajax($action, $datas);
	}
	/**
	 * 接收表单post数据
	 */
	public function post()
	{
		$post = $this->input->post();
		$this->process_ajax($post['action'], $post);
	}
	/**
	 * 处理各种ajax请求
	 * @param unknown $action
	 * @param unknown $datas
	 * @return json
	 */
	private function process_ajax($action, $datas = array())
	{
		$content = ''; $message = ''; $append_data = array();
		$exclude_for_id = array('add', 'insert', 'update', 'query');
		if($action == 'update'){
			$datas['item_id'] = $datas['id'];
		}
		if(!in_array($action, $exclude_for_id) && (!isset($datas['item_id']) || empty($datas['item_id']))){
			make_json_error("未指明操作对象！[305:$action]");
		}
        admin_permissions($action, $this->priv_name . 'edit', $this->priv_name . 'dele');
		$result['error'] = 0;
		switch ($action){
			case 'query':
				$this->datas ['full_page'] = FALSE;
				$content = $this->query_list();
				break;
			case 'hide':
			case 'show':
				$update_datas['is_open'] = $action == 'hide' ? 0 : 1;
				$result = $this->myModel->edit_data($update_datas, $datas['item_id']);
				break;
			default:
				$result['error'] = 300;
				$result['message'] = "非法操作！[".$datas['item_id']."]";
				break;
		}
		if($result['error'] > 0){
			make_json_error($result['message']."\r\n[Err:".$result['error']."]");
		}else{
			make_json_result($content, $message, $append_data);
		}
	}
	
	public function load_regions()
	{
		$get = $this->input->get();
		$type   = isset($get['type']) ? intval($get['type']) : 0;
		$parent = isset($get['parent']) ? intval($get['parent']) : 0;
		$target = isset($get['target']) ? trim($get['target']) : '';
		$selectedId = isset($get['selectedId']) ? intval($get['selectedId']) : 0;
	
		$this->load->model('regions_model');
        if($type == 2){
            $arr['regions'] = $this->regions_model->get_city($parent);
        }else if($type == 3){
            $arr['regions'] = $this->regions_model->get_area($parent);
        }
		
	
		$arr['type']    = $type;
		$arr['target']  = $target;
		$arr['selectedId']    = $selectedId;	
		make_json_result($arr);
	}
	/**
	 * 高德地理编码 地址换进纬度
	 * @link http://restapi.amap.com/v3/geocode/geo?key=ac9a29dd78fc7192a4160d255b7b16cb&s=rsv3&address=上海市虹口区北宝兴路89号
	 * @example
	 * {"status":"1","info":"OK","count":"1","geocodes":[
	 * 	{"formatted_address":"上海市虹口区北宝兴路89号","province":"上海市","citycode":"021","city":"上海市","district":"虹口区",
	 * 	"township":[],"neighborhood":{"name":[],"type":[]},
	 * 	"building":{"name":[],"type":[]},"adcode":"310109","street":"北宝兴路","number":"89号",
	 * 	"location":"121.466460,31.272219","level":"门牌号"}
	 * ]}
	 * @param unknown $address
	 */
	public function amap_location($address)
	{
		$address = urldecode($address);
		//根据经纬度换取地址信息
		$mapApi_url = "http://restapi.amap.com/v3/geocode/geo?key=ac9a29dd78fc7192a4160d255b7b16cb&s=rsv3";
		//$mapApi_url .= "&location=".$Longitude.",".$Latitude;
		//$mapApi_url .= "&radius=1000&extensions=all";
// 		$mapApi_url .= "&address=".rawurlencode("上海市虹口区北宝兴路89号");
		$mapApi_url .= "&address=".rawurlencode($address);
// 		header("Content-type: text/html; charset=utf-8");
		
// 		$amap_str = file_get_contents($mapApi_url);
		
		$this->load->library('user_agent');
		$user_agent = $this->agent->agent_string();
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $mapApi_url);
		//curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
		curl_setopt($ch, CURLINFO_CONTENT_TYPE, 'application/json;charset=UTF-8');
		$amap_str = curl_exec($ch);
		curl_close($ch);
		
		$result = json_decode($amap_str, true);
		if($result['status'] == 1){
			$append_data['count'] = $result['count'];
			$geocodes = $result['geocodes'][0];
			$coords = explode(',', $geocodes['location']);
			//高德gps纠偏 不做纠偏
			//$this->load->library('third_party/gps_correct');
			//$correct_location = $this->gps_correct->transform($coords[0], $coords[1]);
			//$append_data['datas'] = json_encode($geocodes);
			//使用原始数据
			$correct_location = $coords;
			
			$append_data['amap_location'] = $geocodes['location'];
			$append_data['location'] = implode(',', $correct_location);
			$append_data['formatted_address'] = $geocodes['formatted_address'];
			$append_data['lng'] = $correct_location[0];
			$append_data['lat'] = $correct_location[1];
			make_json_result('', 'ok', $append_data);
		}else{
			make_json_error("接口请求失败！\r\nErr:".$result['status']."\r\n".$result['info']);
		}

	}	
	public function gps_correct()
	{
		$gps = $_REQUEST['gps'];
		$coords = explode(',', $gps);
		//高德gps纠偏
		$this->load->library('third_party/gps_correct');
		$correct_location = $this->gps_correct->transform($coords[0], $coords[1]);
		$append_data['correct_coords'] = implode(',', $correct_location);
		$append_data['lng'] = $correct_location[0];
		$append_data['lat'] = $correct_location[1];
		make_json_result('', 'ok', $append_data);
	}
	
	
	

	/**
	 * Socket版本
	* 使用方法：
	* $post_string = "app=socket&version=beta";
	* request_by_socket('chajia8.com', '/restServer.php', $post_string);
	*/
// 	function request_by_socket($remote_server,$remote_path,$post_string = '',$port = 80,$timeout = 30) {
// 		$socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
// 		if (!$socket) die("$errstr($errno)");
// 		fwrite($socket, "POST $remote_path HTTP/1.0");
// 		fwrite($socket, "User-Agent: Socket Example");
// 		fwrite($socket, "HOST: $remote_server");
// 		fwrite($socket, "Content-type: application/x-www-form-urlencoded");
// 		fwrite($socket, "Content-length: " . （strlen($post_string) + 8） . "");
// 		fwrite($socket, "Accept:*/*");
// 		fwrite($socket, "");
// 		fwrite($socket, "mypost=$post_string");
// 		fwrite($socket, "");
// 		$header = "";
// 		$str = trim(fgets($socket, 4096));
// 		while($str){
// 			$header .= $str;
// 		}
// 		$data = "";
// 		while (!feof($socket)) {
// 			$data .= fgets($socket, 4096);
// 		}
// 		return $data;
// 	}

	public function send_post()
	{
		$post = $this->input->post();
		$remote_server 	= (!isset($post['url']) || empty($post['url'])) ? '' : urldecode($post['url']);
		$post_data 		= (!isset($post['post_data']) || empty($post['post_data'])) ? '' : $post['post_data'];
		$post_array 	= json_decode($post['post_data'], TRUE);
// 		make_json_error($remote_server.'请求地址错误！12'.json_encode($post_array));
		if(empty($remote_server)){
			make_json_error('请求地址错误！');
		}
		$result = $this->request_by_curl($remote_server, $post_array);
		
		die($result);
	} 
	/**
	 * Curl版本
	 * 使用方法：
	 * $post_string = "app=request&version=beta";
	 * request_by_curl('http://www.qianyunlai.com/restServer.php', $post_array);
	 */
	function request_by_curl($remote_server, $post_array = array()) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $remote_server);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, "CURL Example beta");
		$data = curl_exec($ch);
		curl_close($ch);
	
		return $data;
	}

}

?>